package com.millstein.smsservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.millstein.servicebase.handler.exceptionhandler.GuliException;
import com.millstein.smsservice.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {


    @Override
    public void send(Map<String, Object> params, String phone) {
        // 1.生成发送短信的客户端
        if (StringUtils.isEmpty(phone)) {
            throw new GuliException(20001, "发送短信时，手机号码不能为空");
        }
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAItMzZiGJMOOrn",
                "luUcqCsxt2vaNZsjHShdUriqFXAbcB");
        IAcsClient client = new DefaultAcsClient(profile);

        // 2.设置固定参数
        CommonRequest request = new CommonRequest();
//        request.setProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setAction("SendSms");

        // 3.设置发送相关的参数
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "艾玛米尔斯汀");
        request.putQueryParameter("TemplateCode", "SMS_160861119");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(params));

        // 4.最终发送

        try {
            CommonResponse res = client.getCommonResponse(request);
            boolean success = res.getHttpResponse().isSuccess();
            if (!success) {
                throw new GuliException(20001, "短信发送失败");
            }
        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001, e.getMessage());
        }
    }
}
